package com.gengealogy.net.controller;



import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gengealogy.net.po.Clan;
import com.gengealogy.net.po.Tree;
import com.gengealogy.net.service.TreeService;

@Controller
public class TreeController {
	@Autowired
	private TreeService treeService;

	public TreeService getTreeService() {
		return treeService;
	}

	public void setTreeService(TreeService treeService) {
		this.treeService = treeService;
	}

	/**
	 * 向族谱页面跳转
	 */
	@RequestMapping(value = "/build/getTree.action")
	public String getTree( Model model, HttpSession session) {
		int tree_clan_id = (int) session.getAttribute("TREE_CLAN_ID");
		Tree tree = treeService.findTree(tree_clan_id);
		if (tree==null) {
			model.addAttribute("msg", "还未创建族谱，请先创建！");
			return "build/create_tree";
		}else {
			model.addAttribute("tree", tree);
		int tree_id = tree.getTree_id();
		session.setAttribute("TREE_ID", tree_id);
		int user_ident = (int) session.getAttribute("USER_IDENT");
		if (user_ident== 0)
			// 跳转到普通用户主页面
			return "user/user_tree";
		else
			return "build/build_tree";
		}
	}

	/**
	 * 向创建族谱页面跳转
	 */
	@RequestMapping(value = "/addTree.action", method = RequestMethod.GET)
	public String toAddTree() {
		return "build/build_tree";
	}

	@RequestMapping(value = "/addTree.action", method = RequestMethod.POST)
	public String addTree(Tree tree, Model model) {
		treeService.addTree(tree);
		return "redirect:build/getTree.action";
	}
	
	@RequestMapping(value = "/tree/updateTree.action", method = RequestMethod.POST)
	@ResponseBody
	public String updateTree(Tree tree, Model model) {
		int rows =treeService.updateTree(tree);
		if(rows > 0){			
	        return "OK";
	    }else{
	        return "FAIL";			
	    }
	}
	
	@RequestMapping("/getTreeById.action")
	@ResponseBody
	public Tree getTreeById(Model model, HttpSession session) {
		int tree_clan_id = (int) session.getAttribute("TREE_CLAN_ID");
		Tree tree = treeService.getTreeById(tree_clan_id);
	    return tree;
	}

}
